import { createStore } from 'vuex'

const setLocalStorage = (state) => {
  const { cartList } = state
  const cartListsTring = JSON.stringify(cartList)
  localStorage.cartList = cartListsTring
}

const getLocalStorage = () => {
  return localStorage.cartList ? JSON.parse(localStorage.cartList) : {}
  // try catch也可
}
export default createStore({
  state: {
    cartList: getLocalStorage()
    // 第一层级是商铺的id
    // shopId: {
    //   shopName: '沃尔玛',
    //   productList: {
    //     productId: {
    //       _id: 1,
    //       name: 'xxx',
    //       imgUrl: '',
    //       sales: 10,
    //       price: 5,
    //       oldPrice: 10,
    //       count: 2
    //     }
    //   }
    // }
  },
  mutations: {
    changeCartItemInfo (state, payload) {
      const { shopId, productId, productInfo, num } = payload
      // let shopInfo = state.cartList[shopId]
      // if (!shopInfo) { shopInfo = {} }
      const shopInfo = state.cartList[shopId] || { shopName: '', productList: {} }
      let product = shopInfo.productList[productId]
      if (!product) {
        product = productInfo
        product.count = 0
      }
      product.count += num
      if (num > 0) { product.check = true }
      if (product.count < 0) { product.count = 0 }
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalStorage(state)
    },
    changeShopName (state, payload) {
      const { shopId, shopName } = payload
      const shopInfo = state.cartList[shopId] || { shopName: '', productList: {} }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLocalStorage(state)
    },
    changeCartItemCheck (state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId].productList[productId]
      product.check = !product.check
      setLocalStorage(state)
    },
    cleanCartProduct (state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLocalStorage(state)
    },
    setCartItemsChecked (state, payload) {
      const { shopId } = payload
      const products = state.cartList[shopId].productList
      if (products) {
        for (const i in products) {
          const product = products[i]
          product.check = true
        }
      }
      setLocalStorage(state)
    },
    // 清空
    clearCartData (state, shopId) {
      state.cartList[shopId].productList = {}
    }
  },
  actions: {
  },
  modules: {
  }
})
